package com.hzzftech.watchdog.busi.controller;

import com.hzzftech.watchdog.busi.constants.BusiConstant;
import com.hzzftech.watchdog.busi.domain.*;
import com.hzzftech.watchdog.busi.service.*;
import com.hzzftech.watchdog.busi.service.impl.KtExecutionLogServiceImpl;
import com.hzzftech.watchdog.busi.service.impl.KtRepositoryServiceImpl;
import com.hzzftech.watchdog.busi.utils.FileUtils;
import com.hzzftech.watchdog.common.annotation.Log;
import com.hzzftech.watchdog.common.core.controller.BaseController;
import com.hzzftech.watchdog.common.core.domain.AjaxResult;
import com.hzzftech.watchdog.common.core.page.TableDataInfo;
import com.hzzftech.watchdog.common.enums.BusinessType;
import com.hzzftech.watchdog.common.utils.poi.ExcelUtil;
import org.apache.commons.codec.binary.Base64;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.pentaho.di.core.exception.KettleMissingPluginsException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.List;
import java.util.Objects;

/**
 * 任务调度Controller
 * 
 * @author liquanxiang
 * @date 2021-12-14
 */
@Controller
@RequestMapping("/busi/dispatcherGit")
public class KtDispatcherGitController extends BaseController
{
    private String prefix = "busi/dispatcherGit";

    @Autowired
    private IKtDispatcherService ktDispatcherService;

    @Autowired
    private IKtRepositoryService repositoryService;

    @Autowired
    private IKtRepositoryNodeService iKtRepositoryNodeService;

    @Autowired
    private IKtParamsGroupService iKtParamsGroupService;

    @Autowired
    private IKtWarnMsgService warnMsgService;

    @RequiresPermissions("busi:dispatcher:view")
    @GetMapping()
    public String dispatcher()
    {
        return prefix + "/dispatcher";
    }

    /**
     * 查询任务调度列表
     */
    @RequiresPermissions("busi:dispatcher:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(KtDispatcher ktDispatcher)
    {
        startPage();
        List<KtDispatcher> list = ktDispatcherService.selectKtDispatcherList(ktDispatcher, BusiConstant.REPOSITORY_TYPE_GIT);
        return getDataTable(list);
    }

    /**
     * 导出任务调度列表
     */
    @RequiresPermissions("busi:dispatcher:export")
    @Log(title = "任务调度", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(KtDispatcher ktDispatcher)
    {
        List<KtDispatcher> list = ktDispatcherService.selectKtDispatcherList(ktDispatcher, BusiConstant.REPOSITORY_TYPE_GIT);
        ExcelUtil<KtDispatcher> util = new ExcelUtil<KtDispatcher>(KtDispatcher.class);
        return util.exportExcel(list, "任务调度数据");
    }

    /**
     * 新增任务调度
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        KtRepository repository = new KtRepository();
        repository.setStatus(BusiConstant.STATUS_YES);
        List<KtRepository> repoList = repositoryService.selectKtRepositoryList(repository);
        // GIT仓库信息
        mmap.addAttribute("repoList", repoList);
        KtRepositoryNode node = new KtRepositoryNode();
        node.setStatus(BusiConstant.STATUS_YES);
        List<KtRepositoryNode> ktRepositoryNodes = iKtRepositoryNodeService.selectKtRepositoryNodeList(node);
        // 调度服务器信息
        mmap.addAttribute("nodeList", ktRepositoryNodes);
        KtParamsGroup group = new KtParamsGroup();
        group.setStatus(BusiConstant.STATUS_YES);
        List<KtParamsGroup> ktParamsGroups = iKtParamsGroupService.selectKtParamsGroupList(group);
        // 调度参数信息
        mmap.addAttribute("pgList", ktParamsGroups);
        List<KtWarnMsg> ktWarnMsgs = warnMsgService.selectKtWarnMsgList(new KtWarnMsg());
        // 运行失败发送预警信息
        mmap.addAttribute("warnList", ktWarnMsgs);
        for (KtWarnMsg msg : ktWarnMsgs) {
            if (msg.getContactType().equals(BusiConstant.CONTACT_TYPE_DINGDING)) {
                msg.setDingWebHook(msg.getDingWebHook().substring(msg.getDingWebHook().length() -20));
            }
        }
        return prefix + "/add";
    }

    /**
     * 新增保存任务调度
     */
    @RequiresPermissions("busi:dispatcher:add")
    @Log(title = "任务调度", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(KtDispatcher ktDispatcher)
    {
        KtDispatcher dispatcher = ktDispatcherService.selectKtDispatcherByDpName(ktDispatcher.getDpName());
        if (!Objects.isNull(dispatcher)) {
            return AjaxResult.error("调度名称重复！");
        }

        ktDispatcherService.addProcess(ktDispatcher);
        return toAjax(ktDispatcherService.insertKtDispatcher(ktDispatcher));
    }

    /**
     * 修改任务调度
     */
    @RequiresPermissions("busi:dispatcher:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        KtDispatcher ktDispatcher = ktDispatcherService.selectKtDispatcherById(id, BusiConstant.REPOSITORY_TYPE_GIT);
        mmap.put("ktDispatcher", ktDispatcher);

        KtRepositoryNode node = new KtRepositoryNode();
        node.setStatus(BusiConstant.STATUS_YES);
        List<KtRepositoryNode> ktRepositoryNodes = iKtRepositoryNodeService.selectKtRepositoryNodeList(node);
        // 运行服务器节点信息
        mmap.addAttribute("nodeList", ktRepositoryNodes);
        KtParamsGroup group = new KtParamsGroup();
        group.setStatus(BusiConstant.STATUS_YES);
        List<KtParamsGroup> ktParamsGroups = iKtParamsGroupService.selectKtParamsGroupList(group);
        // 参数信息
        mmap.addAttribute("pgList", ktParamsGroups);
        List<KtWarnMsg> ktWarnMsgs = warnMsgService.selectKtWarnMsgList(new KtWarnMsg());
        // 运行失败警告信息
        mmap.addAttribute("warnList", ktWarnMsgs);
        for (KtWarnMsg msg : ktWarnMsgs) {
            if (msg.getContactType().equals(BusiConstant.CONTACT_TYPE_DINGDING)) {
                msg.setDingWebHook(msg.getDingWebHook().substring(msg.getDingWebHook().length() -20));
            }
        }
        return prefix + "/edit";
    }

    /**
     * 修改保存任务调度
     */
    @RequiresPermissions("busi:dispatcher:edit")
    @Log(title = "任务调度", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(KtDispatcher ktDispatcher)
    {
        ktDispatcherService.updateProcess(ktDispatcher);
        return toAjax(ktDispatcherService.updateKtDispatcher(ktDispatcher));
    }

    /**
     * 删除任务调度
     */
    @RequiresPermissions("busi:dispatcher:remove")
    @Log(title = "任务调度", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(ktDispatcherService.deleteKtDispatcherByIds(ids));
    }

    @RequiresPermissions("busi:dispatcher:launch")
    @Log(title = "任务调度", businessType = BusinessType.OTHER)
    @PostMapping( "/launchG")
    @ResponseBody
    public AjaxResult startGJobOrTrans(String ids) throws KettleMissingPluginsException, KettleXMLException {
        return toAjax(ktDispatcherService.launchGJob(ids));
    }

    @Autowired
    private IKtExecutionLogService logService;

    @Value("kt-watchdog.git_file_repository_log_file")
    private String LOG_FILE;

    @RequiresPermissions("busi:dispatcher:log")
    @Log(title = "任务调度日志文件", businessType = BusinessType.OTHER)
    @GetMapping( "/img")
    @ResponseBody
    public AjaxResult getKtImg(@RequestParam("id") String id) {
        // 执行任务图片
        KtExecutionLog log = logService.selectKtExecutionLogById(id);
        String logFPath = "";
        if (log.getTaskType().equals(BusiConstant.KETTLE_TYPE_FLAG_TRANS)) {
            logFPath = LOG_FILE + File.separator+"trans"+File.separator+log.getImagePath();
        } else if (log.getTaskType().equals(BusiConstant.KETTLE_TYPE_FLAG_JOB)){
            logFPath = LOG_FILE + File.separator+"job"+File.separator+log.getImagePath();
        }
        File f = new File(logFPath);
        if (!f.exists()) {
            return AjaxResult.error();
        }

        try {
            FileInputStream in = new FileInputStream(f);
            long size = f.length();
            byte[] buffer = new byte[(int)size];
            in.read(buffer, 0, (int)size);
            in.close();
            AjaxResult success = AjaxResult.success();
            success.put("image", Base64.encodeBase64String(buffer));
            return success;
        } catch (Exception e) {
            logger.error("读写文件错误",e);
            return AjaxResult.error("读写文件错误");
        }
    }
}
